<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/5/005
 * Time: 9:10
 */

namespace app\api\model;


use app\api\service\Token;

class Activity extends BaseModel {

    private static $uid;

    protected $hidden = ['update_time','delete_time', 'pid', 'level', 'status', 'sort', 'pay_type', 'pay_time', 'pay_sn'];

    /**
     * 订单用户
     * @return \think\model\relation\BelongsTo
     */
    public function member() {
        return $this->belongsTo('Member');
    }

    /**
     * 活動參與者
     * @return \think\model\relation\HasMany
     */
    public function activityParticipation() {
        return $this->hasMany('ActivityParticipation');
    }

    /**
     * 活动赞助产品
     * @return \think\model\relation\BelongsTo
     */
    public function product() {
        return $this->belongsTo('Product');
    }

    /**
     * 活动赞助产品所在店铺
     * @return \think\model\relation\BelongsTo
     */
    public function shop() {
        return $this->belongsTo('Shop');
    }


    /**
     * 活动状态获取器
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getStatusAttr($value, $data) {
        $now = $data['start_time'] > time() ? '未开始' :  '正在进行';
        $status_array = [
            '', '待支付', $now, '已结束'
        ];
        return $status_array[$value];
    }

    /**
     * 根据条件获取活动分页列表
     * @param $where
     * @return \think\Paginator
     */
    public static function getPageListByWhere($where) {

        self::$uid = Token::getCurrentUid();
        $list = self::where($where)->order('id desc')->paginate('', true);
        $list = self::saveActivityList($list);
        return $list;
    }

    /**
     * 根据条件获取活动分页列表
     * @param $where
     * @return array|\PDOStatement|string|\think\Collection
     */
    public static function getListByWhere($where) {

        self::$uid = Token::getCurrentUid();
        $list = self::where($where)->order('id desc')->select();
        $list = self::saveActivityList($list);
        return $list;
    }

    /**
     * 处理活动列表字段
     * @param $list
     * @return mixed
     */
    private static function saveActivityList($list) {
        foreach ($list as &$v) {
            $v->member->visible(['memberRoleInfo'])->memberRoleInfo->visible(['nickname', 'headimgurl']);
            $v->my_activity = $v->member_id == self::$uid ? '我发起的' : '';
            $v->image_1 = get_img_url($v->image_1);
            $v->image_2 = get_img_url($v->image_2);
            $v->image_3 = get_img_url($v->image_3);
            $v->application_time = time_tran($v->create_time);
        }
        return $list;
    }
}